import {defineStore} from 'pinia';
import {readonly, ref} from 'vue';
//导入全局状态-订单信息
import { useDetailStore, type OrderInfoContent } from './detail';

//定义订单信息缓存类型
interface OrderInfoCache{
    [index:number]:OrderInfoContent,
    length:number
}
//定义全局变量-订单缓存
export const useCacheStore=defineStore('cache',()=>{
    //初始化缓存内容
    const key:string='ChickenPotOrderCache';
    const content=ref<OrderInfoCache>({length:0});
    //加载本地缓存
    if(key in localStorage){
        Object.assign(content.value,JSON.parse(localStorage[key]));
    }
    //更新缓存方法
    function update(data:OrderInfoContent):void{
        //生成缓存条目
        const orderCacheItem={} as OrderInfoCache;
        const id=useDetailStore().id as number;
        orderCacheItem[id]=JSON.parse(JSON.stringify(data));
        //根据缓存长度判断是否清除多余缓存
        if(++content.value.length>10){
            const outOfDate=Number(Object.keys(content.value).filter(key=>key!=='length')[0]);
            delete (content.value)[outOfDate];
            content.value.length--;
        }
        //插入缓存条目
        Object.assign(content.value,orderCacheItem);
        //更新本地缓存
        localStorage.setItem(key,JSON.stringify(content.value));
    }
    return {
        content:readonly(content),
        update
    };
});
